import { useState, useEffect } from 'react';
import {
  Alert,
  Box,
  Button,
  Card,
  Chip,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  Grid,
  IconButton,
  InputLabel,
  MenuItem,
  Pagination,
  Paper,
  Select,
  Snackbar,
  Stack,
  TextField,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip
} from '@mui/material';
import {
  Delete as DeleteIcon,
  PushPin as PushPinIcon,
  Reply as ReplyIcon,
  Visibility as VisibilityIcon,
  Search as SearchIcon
} from '@mui/icons-material';
import ToolPageTemplate from '@/components/ToolPageTemplate';
import { useMessage } from '@/hooks/tools/useMessage';

const MessageAdmin = () => {
  const {
    messages,
    loading,
    error,
    total,
    getAdminMessages,
    auditMessage,
    deleteMessage,
    topMessage,
    getMessageStats,
    clearError
  } = useMessage();

  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(15);
  const [statusFilter, setStatusFilter] = useState<number | ''>('');
  const [keyword, setKeyword] = useState('');
  const [searchKeyword, setSearchKeyword] = useState('');
  
  // 对话框状态
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [replyDialogOpen, setReplyDialogOpen] = useState(false);
  const [selectedMessage, setSelectedMessage] = useState<any>(null);
  const [replyContent, setReplyContent] = useState('');
  const [auditStatus, setAuditStatus] = useState<1 | 2>(1);
  
  // 统计数据
  const [stats, setStats] = useState<any>({});
  
  // 提示状态
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error'>('success');

  useEffect(() => {
    loadMessages();
    loadStats();
  }, [currentPage, statusFilter, searchKeyword]);

  const loadMessages = () => {
    getAdminMessages(currentPage, pageSize, statusFilter || undefined, searchKeyword || undefined);
  };

  const loadStats = async () => {
    try {
      const statsData = await getMessageStats();
      setStats(statsData);
    } catch (err) {
      console.error('获取统计数据失败:', err);
    }
  };

  const handleSearch = () => {
    setSearchKeyword(keyword);
    setCurrentPage(1);
  };

  const handleStatusFilterChange = (value: number | '') => {
    setStatusFilter(value);
    setCurrentPage(1);
  };

  const handleViewDetail = (message: any) => {
    setSelectedMessage(message);
    setDetailDialogOpen(true);
  };

  const handleReply = (message: any) => {
    setSelectedMessage(message);
    setReplyContent('');
    setAuditStatus(1);
    setReplyDialogOpen(true);
  };

  const handleAudit = async () => {
    if (!selectedMessage) return;

    try {
      await auditMessage(selectedMessage.id, auditStatus, replyContent || undefined);
      setReplyDialogOpen(false);
      showSnackbar('审核成功', 'success');
      loadMessages();
      loadStats();
    } catch (err: any) {
      showSnackbar(err.message || '审核失败', 'error');
    }
  };

  const handleDelete = async (messageId: number) => {
    if (!confirm('确定要删除这条留言吗？')) return;

    try {
      await deleteMessage(messageId);
      showSnackbar('删除成功', 'success');
      loadMessages();
      loadStats();
    } catch (err: any) {
      showSnackbar(err.message || '删除失败', 'error');
    }
  };

  const handleTop = async (messageId: number, isTop: number) => {
    try {
      const newTopStatus = isTop === 1 ? 0 : 1;
      await topMessage(messageId, newTopStatus);
      showSnackbar(newTopStatus === 1 ? '置顶成功' : '取消置顶成功', 'success');
      loadMessages();
    } catch (err: any) {
      showSnackbar(err.message || '操作失败', 'error');
    }
  };

  const handlePageChange = (_: React.ChangeEvent<unknown>, value: number) => {
    setCurrentPage(value);
  };

  const showSnackbar = (message: string, severity: 'success' | 'error') => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setSnackbarOpen(true);
  };

  const getStatusColor = (status: number) => {
    switch (status) {
      case 0: return 'warning';
      case 1: return 'success';
      case 2: return 'error';
      default: return 'default';
    }
  };

  const totalPages = Math.ceil(total / pageSize);

  return (
    <ToolPageTemplate
      title="留言管理"
      description="管理用户留言，审核和回复"
      category="管理工具"
      categoryColor="#6B73FF"
    >
      {/* 统计卡片 */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid item xs={12} sm={6} md={3}>
          <Card sx={{ textAlign: 'center', p: 2 }}>
            <Typography variant="h4" color="primary" sx={{ fontWeight: 700 }}>
              {stats.total || 0}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              总留言数
            </Typography>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Card sx={{ textAlign: 'center', p: 2 }}>
            <Typography variant="h4" color="warning.main" sx={{ fontWeight: 700 }}>
              {stats.pending || 0}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              待审核
            </Typography>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Card sx={{ textAlign: 'center', p: 2 }}>
            <Typography variant="h4" color="success.main" sx={{ fontWeight: 700 }}>
              {stats.approved || 0}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              已通过
            </Typography>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Card sx={{ textAlign: 'center', p: 2 }}>
            <Typography variant="h4" color="error.main" sx={{ fontWeight: 700 }}>
              {stats.rejected || 0}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              已拒绝
            </Typography>
          </Card>
        </Grid>
      </Grid>

      {/* 搜索和筛选 */}
      <Paper sx={{ p: 3, mb: 4 }}>
        <Grid container spacing={3} alignItems="center">
          <Grid item xs={12} md={4}>
            <TextField
              fullWidth
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              placeholder="搜索昵称、内容或邮箱..."
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            />
          </Grid>
          <Grid item xs={12} md={3}>
            <FormControl fullWidth>
              <InputLabel>状态筛选</InputLabel>
              <Select
                value={statusFilter}
                onChange={(e) => handleStatusFilterChange(e.target.value as number | '')}
                label="状态筛选"
              >
                <MenuItem value="">全部状态</MenuItem>
                <MenuItem value={0}>待审核</MenuItem>
                <MenuItem value={1}>已通过</MenuItem>
                <MenuItem value={2}>已拒绝</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={2}>
            <Button
              fullWidth
              variant="contained"
              startIcon={<SearchIcon />}
              onClick={handleSearch}
            >
              搜索
            </Button>
          </Grid>
        </Grid>
      </Paper>

      {/* 留言列表 */}
      <Paper>
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>昵称</TableCell>
                <TableCell>留言内容</TableCell>
                <TableCell>状态</TableCell>
                <TableCell>创建时间</TableCell>
                <TableCell>IP地址</TableCell>
                <TableCell align="center">操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={6} align="center">
                    加载中...
                  </TableCell>
                </TableRow>
              ) : messages.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} align="center">
                    暂无数据
                  </TableCell>
                </TableRow>
              ) : (
                messages.map((message) => (
                  <TableRow key={message.id}>
                    <TableCell>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        {message.nickname}
                        {message.isTop === 1 && (
                          <PushPinIcon fontSize="small" color="warning" />
                        )}
                      </Box>
                    </TableCell>
                    <TableCell>
                      <Typography 
                        sx={{ 
                          maxWidth: 300,
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap'
                        }}
                      >
                        {message.content}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip
                        label={message.statusDesc}
                        color={getStatusColor(message.status)}
                        size="small"
                      />
                    </TableCell>
                    <TableCell>
                      {message.createTimeDisplay}
                    </TableCell>
                    <TableCell>
                      {message.ipAddress}
                    </TableCell>
                    <TableCell>
                      <Stack direction="row" spacing={1}>
                        <Tooltip title="查看详情">
                          <IconButton
                            size="small"
                            onClick={() => handleViewDetail(message)}
                          >
                            <VisibilityIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                        {message.status === 0 && (
                          <Tooltip title="审核回复">
                            <IconButton
                              size="small"
                              color="primary"
                              onClick={() => handleReply(message)}
                            >
                              <ReplyIcon fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        )}
                        <Tooltip title={message.isTop === 1 ? '取消置顶' : '置顶'}>
                          <IconButton
                            size="small"
                            color={message.isTop === 1 ? 'warning' : 'default'}
                            onClick={() => handleTop(message.id, message.isTop)}
                          >
                            <PushPinIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="删除">
                          <IconButton
                            size="small"
                            color="error"
                            onClick={() => handleDelete(message.id)}
                          >
                            <DeleteIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      </Stack>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </TableContainer>

        {/* 分页 */}
        {totalPages > 1 && (
          <Box sx={{ p: 3, display: 'flex', justifyContent: 'center' }}>
            <Pagination
              count={totalPages}
              page={currentPage}
              onChange={handlePageChange}
              color="primary"
              shape="rounded"
              showFirstButton
              showLastButton
            />
          </Box>
        )}
      </Paper>

      {/* 详情对话框 */}
      <Dialog
        open={detailDialogOpen}
        onClose={() => setDetailDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>留言详情</DialogTitle>
        <DialogContent>
          {selectedMessage && (
            <Stack spacing={3}>
              <Box>
                <Typography variant="subtitle2" gutterBottom>
                  昵称：
                </Typography>
                <Typography>{selectedMessage.nickname}</Typography>
              </Box>
              <Box>
                <Typography variant="subtitle2" gutterBottom>
                  邮箱：
                </Typography>
                <Typography>{selectedMessage.email || '未提供'}</Typography>
              </Box>
              <Box>
                <Typography variant="subtitle2" gutterBottom>
                  留言内容：
                </Typography>
                <Typography sx={{ whiteSpace: 'pre-wrap' }}>
                  {selectedMessage.content}
                </Typography>
              </Box>
              {selectedMessage.reply && (
                <Box>
                  <Typography variant="subtitle2" gutterBottom>
                    管理员回复：
                  </Typography>
                  <Typography sx={{ whiteSpace: 'pre-wrap' }}>
                    {selectedMessage.reply}
                  </Typography>
                </Box>
              )}
              <Box>
                <Typography variant="subtitle2" gutterBottom>
                  其他信息：
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  IP地址：{selectedMessage.ipAddress}<br />
                  创建时间：{selectedMessage.createTime}<br />
                  点赞数：{selectedMessage.likeCount}
                </Typography>
              </Box>
            </Stack>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDetailDialogOpen(false)}>
            关闭
          </Button>
        </DialogActions>
      </Dialog>

      {/* 审核回复对话框 */}
      <Dialog
        open={replyDialogOpen}
        onClose={() => setReplyDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>审核留言</DialogTitle>
        <DialogContent>
          <Stack spacing={3}>
            <FormControl fullWidth>
              <InputLabel>审核结果</InputLabel>
              <Select
                value={auditStatus}
                onChange={(e) => setAuditStatus(e.target.value as 1 | 2)}
                label="审核结果"
              >
                <MenuItem value={1}>通过</MenuItem>
                <MenuItem value={2}>拒绝</MenuItem>
              </Select>
            </FormControl>
            <TextField
              fullWidth
              multiline
              rows={4}
              value={replyContent}
              onChange={(e) => setReplyContent(e.target.value)}
              label="回复内容（可选）"
              placeholder="请输入回复内容..."
            />
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setReplyDialogOpen(false)}>
            取消
          </Button>
          <Button onClick={handleAudit} variant="contained">
            提交审核
          </Button>
        </DialogActions>
      </Dialog>

      {/* 错误提示 */}
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={clearError}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert severity="error" onClose={clearError} sx={{ width: '100%' }}>
          {error}
        </Alert>
      </Snackbar>

      {/* 操作结果提示 */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={() => setSnackbarOpen(false)}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert severity={snackbarSeverity} sx={{ width: '100%' }}>
          {snackbarMessage}
        </Alert>
      </Snackbar>
    </ToolPageTemplate>
  );
};

export default MessageAdmin;